package com.xiangban.yanglaodajie_platform.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.xiangban.yanglaodajie_platform.config.AliYunParameterConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author manke
 * @Date 2020/8/31 10:17
 * @Version 0.0.1
 */
@Configuration
public class OssUtil {
    protected final Logger log = LoggerFactory.getLogger(OssUtil.class);


    @Autowired
    private AliYunParameterConfig aliYunParameterConfig;
    private static OssUtil ossUtil;

    @PostConstruct
    public void init() {
        ossUtil = this;
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    public String uploadImg2Oss(MultipartFile file,HttpServletRequest request) {
        if (file.getSize() > 1024 * 1024 * 20) {
            return "文件过大";
        }
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String substring = "";
        String contentType = request.getHeader("ContentType");
        if (!"image/jpg".equals(contentType)) {
            substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        }else {
            substring=".png";
        }

        String name = UUID.randomUUID().toString().replace("-", "") + substring;

        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name,request);
            return name;
        } catch (Exception e) {
            return "上传失败";
        }
    }

    /**
     * 上传获取fileUrl
     *
     * @param instream
     * @param fileName
     * @return
     */
    private String uploadFile2OSS(InputStream instream, String fileName,HttpServletRequest request) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(ossUtil.aliYunParameterConfig.getEndpoint(), ossUtil.aliYunParameterConfig.getAccessKeyId(), ossUtil.aliYunParameterConfig.getAccessKeySecret());
            String substring = "";
            String contentType = request.getHeader("ContentType");
            if (!"image/jpg".equals(contentType)) {
                substring = fileName.substring(fileName.lastIndexOf("."));
            }else {
                substring=".png";
            }

            if (".jpg".equals(substring) || ".png".equals(substring) || ".jpeg".equals(substring)) {
                PutObjectResult putResult = ossClient.putObject(ossUtil.aliYunParameterConfig.getBucketName(), ossUtil.aliYunParameterConfig.getFileImage() + fileName, instream, objectMetadata);
                ret = putResult.getETag();

            } else {
                PutObjectResult putResult = ossClient.putObject(ossUtil.aliYunParameterConfig.getBucketName(), ossUtil.aliYunParameterConfig.getFile() + fileName, instream, objectMetadata);
                ret = putResult.getETag();
            }

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        return "";
    }

    /**
     * 获取图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            String substring = fileUrl.substring(fileUrl.lastIndexOf("."));
            if (".jpg".equals(substring) || ".png".equals(substring) || ".jpeg".equals(substring)) {
                return this.getUrl(ossUtil.aliYunParameterConfig.getFileImage() + split[split.length - 1]);
            } else {
                return this.getUrl(ossUtil.aliYunParameterConfig.getFile() + split[split.length - 1]);
            }

        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        OSSClient ossClient = new OSSClient(ossUtil.aliYunParameterConfig.getEndpoint(),
                ossUtil.aliYunParameterConfig.getAccessKeyId(), ossUtil.aliYunParameterConfig.getAccessKeySecret());
        URL url = ossClient.generatePresignedUrl(ossUtil.aliYunParameterConfig.getBucketName(), key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }


    /**
     * 多图片上传
     *
     * @param fileList
     * @return
     */
    public String checkList(List<MultipartFile> fileList,HttpServletRequest request) {
        String fileUrl = "";
        String str = "";
        StringBuilder photoUrl = new StringBuilder();
        for (int i = 0; i < fileList.size(); i++) {
            fileUrl = uploadImg2Oss(fileList.get(i),request);
            str = getImgUrl(fileUrl);
            if (i == 0) {
                photoUrl = new StringBuilder(str);
            } else {
                photoUrl.append(",").append(str);
            }
        }
        return photoUrl.toString().trim();
    }

    /**
     * 单个图片上传
     *
     * @param file
     * @return
     */
    public String checkImage(MultipartFile file,HttpServletRequest request) {
        String fileUrl = uploadImg2Oss(file,request);
        String str = getImgUrl(fileUrl);
        return str.trim();
    }
}
